import React from 'react';
import Item from "./item/item";

import { cloneDeep } from "lodash";

import "./index.css";
class Tree extends React.Component {
    constructor(props) {
        super(props);
    }
    state = {
        flatSelectTree: [],
    };
    componentDidMount() {
        var list = this.flatTree(this.props.tree);
        this.setState({
            flatSelectTree: list,
        });
    }
    flatTree(list, level = 0, parent = null) {
        return list.map(item => {
            var node = {
                ...item,
                selected: false,
                expand: false,
                checked: false,
                parent,
                level,
                children: item.children || []
            };
            if (node.expand && node.children.length) {
                node.children = this.flatTree(node.children, level + 1, item.value);
            }
            return node;
        });
    }
    changeNode(node) {
        var list = cloneDeep(node.children);
        return list.map(item => {
            var n = {
                ...item,
                selected: false,
                expand: false,
                checked: false,
                parent: node.parent,
                level: node.level + 1,
                children: item.children || []
            }
            return n;
        });
    }
    stopNode(node, list) {
        var rl = (ls) => {
            list.forEach(item => {
                
            })
        }
        rl(list);
    }
    onIcon(node) {
        var { flatSelectTree } = this.state;
        node.expand = !node.expand;
        if (node.expand) {
            if (node.children.length) {
                var arr = this.changeNode(node);
                var index = flatSelectTree.findIndex(item => item.value === node.value);
                if (index > -1) {
                    flatSelectTree.splice(index + 1, 0, ...arr);
                }
            }
        } else {
            this.stopNode(node, flatSelectTree);
        }

        this.setState({
            flatSelectTree
        });
    }
    render() {
        var { flatSelectTree } = this.state;
        return <div className="tree-container">
            <div className="tree-item">
                {
                    flatSelectTree.map((item, index) =>
                        <Item key={index}
                            node={item}
                            onIcon={this.onIcon.bind(this)} />
                    )
                }
            </div>
        </div>
    }
}


export default Tree;